const flarum = require("../flarum");
const POST = "POST"
const DELETE = "DELETE"
const GET = "GET"
const PUT = "PUT"
const PATCH = "PATCH"

/**
 * 获取请求Header头
 * @returns {{}}
 */
const _header = (headers = {}) => {
    let header = {}
    const identity = wx.getStorageSync("users-identity")
    if (identity) {
        header["Authorization"] = `Token ${identity.identity}`
    }
    header["content-type"] = "application/json"

    return Object.assign(header, headers)
}

/**
 * HTTP默认方法
 * @param url
 * @param param
 * @param other
 * @returns {Promise<unknown>}
 */
const _http = ({ url = '', param = {}, ...other } = {}) => {
    wx.showLoading({
        title: '数据加载中'
    });
    let timeStart = Date.now();
    console.log(`Alistar request ${url} `, JSON.stringify(other))
    return new Promise((resolve, reject) => {
        wx.request({
            url: url,
            data: param,
            ...other,
            complete: (res) => {
                wx.hideLoading();
                const statusCode = res.statusCode
                console.log(`耗时 ${Date.now() - timeStart}`);
                if (statusCode >= 200 && statusCode < 300) {
                    resolve(res.data)
                } else {
                    if (statusCode === 401) {
                        wx.showToast({
                            title: '获取用户信息失败',
                            icon: 'error',
                            duration: 2000
                        })
                        return
                    }
                    reject(res)
                }
            }
        })
    })
}

/**
 * GET请求
 * @param url
 * @param header
 * @returns {Promise<unknown>}
 */
const get = (url, header = {}) => {
    const h = _header(header)
    return _http({
        url,
        method: GET,
        header: h
    })
}

/**
 * POST请求
 * @param url
 * @param param
 * @param header
 * @returns {Promise<unknown>}
 */
const post = (url, param = {}, header = {}) => {
    const h = _header(header)
    return _http({
        url,
        param,
        method: POST,
        header: h
    })
}

/**
 * PATCH请求
 * @param url
 * @param param
 * @param header
 * @returns {Promise<unknown>}
 */
const patch = (url, param = {}, header = {}) => {
    const h = _header(header)
    return _http({
        url,
        param,
        method: PATCH,
        header: h
    })
}

/**
 * PUT请求
 * @param url
 * @param param
 * @param header
 * @returns {Promise<unknown>}
 */
const put = (url, param = {}, header = {}) => {
    const h = _header(header)
    return _http({
        url,
        param,
        method: PUT,
        header: h
    })
}

/**
 * 删除方法
 * @param url
 * @param param
 * @param header
 * @returns {Promise<*>}
 * @constructor
 */
const D = (url, param = {}, header = {}) => {
    const h = _header(header)
    return _http({
        url,
        param,
        method: DELETE,
        header: h
    })
}

module.exports = {
    get, post, put, patch, D
}